//
//  GestureaSectionHeadView.swift
//  EasePods
//
//  Created by 李然 on 2024/5/10.
//

import UIKit

class GestureaSectionHeadView: View {
    
    public var unfoldBlock: ((Bool)->Void)?
    
    private var isUnfolded = false

    override func makeUI() {
        super.makeUI()
        
        self.addSubview(titleLabel)
        self.addSubview(selecLabel)
        self.addSubview(iconImageView)
        self.addSubview(linView)

        self.isUserInteractionEnabled = true
        self.addOnClickListener(target: self, action: #selector(handTap))
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(25)
            make.leading.equalToSuperview().offset(20)
            make.bottom.equalToSuperview().offset(-25)
        }
        
        iconImageView.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-20)
            make.centerY.equalToSuperview()
        }
        
        selecLabel.snp.makeConstraints { make in
            make.trailing.equalTo(iconImageView.snp.leading).offset(-6)
            make.centerY.equalToSuperview()
        }
        
        linView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.height.equalTo(0.5)
            make.leading.trailing.equalToSuperview()
        }
    }
    
    func bind(to model: GestureSectionModel) {
        titleLabel.text = model.buttonMode.title
        isUnfolded = !model.items.isEmpty
        model.selectFuncTypeRelay.map{ $0.title }.bind(to: selecLabel.rx.text).disposed(by: rx.disposeBag)
    }
    
    @objc private func handTap() {
        
        self.rotatedButton()
        self.unfoldBlock?(self.isUnfolded)
    }
    
    private func rotatedButton() {
        
        UIView.animate(withDuration: 0.3) {
            if self.isUnfolded {
                self.iconImageView.transform = .identity
            } else {
                self.iconImageView.transform = self.iconImageView.transform.rotated(by: .pi)
            }
            self.isUnfolded = !self.isUnfolded
        }
    }
    
    private lazy var titleLabel: Label = {
        let label = Label()
        label.font = Fonts.systemFont(ofSize: 14)
        label.textColor = R.color.common_3_text()
        return label
    }()
    
    private lazy var selecLabel: Label = {
        let label = Label()
        label.font = Fonts.systemFont(ofSize: 14)
        label.textColor = R.color.common_11_text_list()
        return label
    }()
    
    private lazy var iconImageView: ImageView = {
        let imageView = ImageView()
        imageView.image = R.image.ic_common_list_fold()
        return imageView
    }()
    
    private lazy var linView: View = {
        let view = View()
        view.backgroundColor = R.color.common_6_line()
        return view
    }()
}
